import FormModal from '@/components/FormModal/index.jsx';
import { Form, Input, Radio } from 'antd';
import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import ModalUtil from '@/utils/modal.js';
import { RoleApi } from '@/api/role/api.js';
import PermissionSelect from '@/pages/RoleManage/widget/PermissionSelect/index.jsx';
import { MODIFY_PERMISSION_ROLE_IDS } from '@/constants/CommonConstant.js';

function RoleFormModal({ onRefresh }, ref) {
  useImperativeHandle(ref, () => ({
    openEdit: (data) => openEdit(data),
    openAdd: () => openAdd(),
    close: () => formRef.current?.close()
  }));

  const [form] = Form.useForm();
  const [isEdit, setIsEdit] = useState(false);
  const formRef = useRef(null);
  const [updateId, setUpdateId] = useState();

  // 打开编辑弹窗
  function openEdit(data) {
    setIsEdit(true);
    if (data.roleId == null) {
      setIsEdit(false);
      ModalUtil.error('数据ID丢失，请刷新重试');
      return;
    }
    setUpdateId(data.roleId);
    formRef.current?.open();
    form.setFieldsValue(data);
  }

  // 打开新增弹窗
  function openAdd() {
    setIsEdit(false);
    formRef.current?.open();
    form?.resetFields();
  }

  // 提交表单
  const handleSubmit = async (values) => {
    let isSuccess = false;
    handleBeforeSubmit(values);
    if (isEdit) {
      const { code } = await RoleApi.update(updateId, values);
      if (code === 0) {
        isSuccess = true;
      }
    } else {
      const { code } = await RoleApi.add(values);
      if (code === 0) {
        isSuccess = true;
      }
    }
    if (isSuccess) {
      ModalUtil.success('操作成功');
      form?.resetFields();
      onRefresh && onRefresh();
      formRef.current?.close();
    }
  };

  // 提交表单前置处理
  const handleBeforeSubmit = (values) => {
    if (Array.isArray(values?.permissionList) && values?.permissionList?.length > 0) {
      // 判断数组的值是否为字符串
      if (typeof values.permissionList[0] != 'string') {
        const permissionList = values.permissionList.map((item) => item?.permissionCode);
        values.permissionList = permissionList.filter((item) => item != null);
      }
    }
  };

  return (
    <FormModal
      form={form}
      ref={formRef}
      name="roleForm"
      title={isEdit ? '编辑角色' : '新增角色'}
      onFinish={handleSubmit}
      formItems={
        <>
          <Form.Item
            name="roleName"
            label="角色名称"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input disabled={MODIFY_PERMISSION_ROLE_IDS.includes(updateId)} />
          </Form.Item>
          <Form.Item
            name="roleCode"
            label="角色代码"
            rules={[{ required: true, message: '请输入角色代码' }]}
          >
            <Input disabled={isEdit && MODIFY_PERMISSION_ROLE_IDS.includes(updateId)} />
          </Form.Item>
          <Form.Item
            name="roleDesc"
            label="角色说明"
            rules={[{ required: true, message: '请输入角色说明' }]}
          >
            <Input.TextArea disabled={MODIFY_PERMISSION_ROLE_IDS.includes(updateId)} />
          </Form.Item>
          <Form.Item
            name="permissionList"
            label="拥有的权限"
            getValueProps={(value) => {
              if (Array.isArray(value)) {
                value = value.map((item) => {
                  // 如果是对象，则取对象的permissionCode字段，否则直接返回
                  return typeof item === 'object' ? item?.permissionCode : item;
                });
              }
              return { value: value };
            }}
          >
            <PermissionSelect />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
            initialValue="1"
          >
            <Radio.Group
              disabled={MODIFY_PERMISSION_ROLE_IDS.includes(updateId)}
              options={[
                { label: '启用', value: '1' },
                { label: '禁用', value: '2' }
              ]}
              optionType="button"
              buttonStyle="solid"
            />
          </Form.Item>
        </>
      }
    />
  );
}

export default forwardRef(RoleFormModal);
